<template>
  <div class="chat-container">
    <!-- 顶部标题和切换按钮 -->
    <div class="top-header">
      <h2>{{ currentView === 'messageList' ? '消息列表' : '好友列表' }}</h2>
      <!-- 视图切换器 -->
      <div class="view-switcher">
        <!-- 消息列表按钮 -->
        <button
            :class="['view-btn', currentView === 'messageList' ? 'active' : '']"
            @click="switchView('messageList')"
        >
          消息
        </button>
        <!-- 好友列表按钮 -->
        <button
            :class="['view-btn', currentView === 'friendList' ? 'active' : '']"
            @click="switchView('friendList')"
        >
          好友
        </button>
      </div>
    </div>

    <!-- 动态组件渲染 -->
    <!-- 消息列表页面 -->
    <MessageList
        v-if="currentView === 'messageList'"
    />

    <!-- 好友列表页面 -->
    <FriendList
        v-else
        :friends="friends"
    />

    <!-- 底部留白，防止内容被底部导航遮挡 -->
    <div class="bottom-spacing"></div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import FriendList from './FriendList.vue'
import MessageList from './MessageList.vue'

export default {
  name: 'Message',
  components: {
    FriendList,
    MessageList,
  },
  setup() {
    const route = useRoute()
    const friends = ref([]) // 好友列表数据
    const currentView = ref('messageList') // 当前视图状态

    /**
     * 初始化视图状态
     * 从URL参数中获取视图设置
     */
    const initializeView = () => {
      const urlParams = new URLSearchParams(window.location.search)
      const view = urlParams.get('view')
      if (view === 'friendList') {
        currentView.value = 'friendList'
      } else {
        currentView.value = 'messageList'
      }
    }

    /**
     * 从localStorage获取token
     * @returns {string|null} 用户token
     */
    const getToken = () => {
      return localStorage.getItem('token')
    }

    /**
     * 检查登录状态
     * @returns {boolean} 是否已登录
     */
    const checkLogin = () => {
      const token = getToken()
      if (!token) {
        // 未登录跳转到登录页
        window.location.href = '/login'
        return false
      }
      return true
    }

    /**
     * 获取当前用户信息
     */
    const getCurrentUser = async () => {
      if (!checkLogin()) return // 检查登录状态

      try {
        const response = await fetch('/api/users/getUserInfo', {
          headers: {
            'token': getToken()
          }
        })
        const result = await response.json()

        if (result.code === 200) {
          // 获取用户信息成功后加载好友列表
          loadFriends()
        } else {
          alert('获取用户信息失败: ' + result.msg)
          // 清除无效token并跳转登录页
          localStorage.removeItem('token')
          window.location.href = '/login'
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        alert('网络错误，请重试')
      }
    }

    /**
     * 加载好友列表
     */
    const loadFriends = async () => {
      try {
        // 获取好友ID列表
        const response = await fetch('/api/userFriends/selFriendsById', {
          headers: {
            'token': getToken()
          }
        })
        const result = await response.json()

        if (result.code === 200) {
          const friendIds = result.data
          // 并行获取每个好友的详细信息
          const friendPromises = friendIds.map(id =>
              fetch(`/api/users/selById?userId=${id}`, {
                headers: {'token': getToken()}
              }).then(res => res.json())
          )

          const friendResults = await Promise.all(friendPromises)
          // 过滤成功的结果并提取数据
          friends.value = friendResults
              .filter(result => result.code === 200)
              .map(result => result.data)
        }
      } catch (error) {
        console.error('加载好友列表失败:', error)
      }
    }

    /**
     * 切换视图
     * @param {string} view - 要切换的视图名称
     */
    const switchView = (view) => {
      currentView.value = view
      // 更新URL参数但不刷新页面（前端路由）
      const newUrl = `${window.location.pathname}?view=${view}`
      window.history.pushState({ path: newUrl }, '', newUrl)
    }

    // 组件挂载后执行
    onMounted(() => {
      initializeView() // 初始化视图状态
      if (checkLogin()) {
        getCurrentUser() // 获取当前用户信息
      }
    })

    return {
      friends,
      currentView,
      switchView
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px; /* 最大宽度限制 */
  margin: 0 auto; /* 居中显示 */
  background: white;
  height: 100vh; /* 全屏高度 */
  display: flex;
  flex-direction: column;
  position: relative;
}

.top-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0; /* 防止头部被压缩 */
}

.top-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.view-switcher {
  display: flex;
  background: #e9ecef; /* 切换器背景色 */
  border-radius: 20px; /* 圆角 */
  padding: 4px;
}

.view-btn {
  padding: 6px 16px;
  border: none;
  background: transparent; /* 透明背景 */
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease; /* 过渡动画 */
}

.view-btn.active {
  background: #007bff; /* 激活状态背景色 */
  color: white;
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2); /* 阴影效果 */
}

.bottom-spacing {
  height: 30px; /* 底部留白高度 */
  flex-shrink: 0;
}

/* 大屏响应式样式 */
@media (max-width: 2000px) {
  .chat-container {
    max-width: 100%; /* 全宽度 */
  }

  .top-header {
    padding: 12px;
  }

  .top-header h2 {
    font-size: 16px;
  }

  .view-btn {
    padding: 5px 12px;
    font-size: 13px;
  }
}
</style>